package com.example.dmservice.auth;

import com.example.dmcommom.AuthException;
import com.example.dmcommom.SpringBeanHelper;
import com.example.dmcommom.TimeUtil;
import com.example.dmdomain.AccountStrategyRepository;
import com.example.dmdomain.UserRepository;
import com.example.dmdomain.entity.AccountStrategy;
import com.example.dmdomain.entity.User;
import com.example.dmservice.exceloutput.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.Calendar;
import java.util.Date;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

@Service
@Slf4j
public class AuthService {

	public boolean checkPermission(User user) throws AuthException {

		if (user.getAuthEndTime() != null) {
			return !user.getAuthEndTime().before(new Date());
		}

		AccountStrategyRepository repository = SpringBeanHelper.getBeanOrThrow(AccountStrategyRepository.class);
		Map<Integer, AccountStrategy> strategies = repository.findAll().stream().collect(Collectors.toMap(AccountStrategy::getUserType,
				Function.identity()));

		AccountStrategy strategy = strategies.get(user.getAccountType());

		switch (strategy.getType()) {
			case AccountStrategy.TYPE_BY_HOUR:
				return checkByHour(strategy);
			case AccountStrategy.TYPE_BY_INTERVAL:
				return checkByInterval(user, strategy);
		}
		return true;
	}

	public boolean checkPermission(String userId) throws AuthException {
		UserRepository userService = SpringBeanHelper.getBeanOrThrow(UserRepository.class);
		User user = userService.findUsersByUserID(userId);
		if (user == null) {
			return false;
		}

		return checkPermission(user);
	}

	private static boolean checkByInterval(User user, AccountStrategy strategy) {
		Date now = new Date();
		Calendar c = Calendar.getInstance();
		c.setTime(user.getCreateTime());
		c.add(Calendar.MILLISECOND, strategy.getInterval());
		if (now.after(c.getTime())) {
			throw new AuthException("账户未授权，请联系管理员授权");
		}
		return true;
	}

	private static boolean checkByHour(AccountStrategy strategy) {
		Date now = TimeUtil.getHHmmDate(new Date());
		if (now == null) {
			return false;
		}
		if (now.before(strategy.getStartTime()) || now.after(strategy.getEndTime())) {
			throw new AuthException("账户未授权，请联系管理员授权");
		}
		return true;
	}
}
